package com.example.servlet;

import com.alibaba.fastjson2.JSON;
import com.example.entity.Pet;
import com.example.enums.PetBreedEnum;
import com.example.service.PetService;
import com.example.service.impl.PetServiceImpl;
import com.example.util.AjaxResult;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@WebServlet("/petServlet")
public class PetServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PetService petService = new PetServiceImpl();
        //品种
        String petBreed = req.getParameter("petBreed");
        List<Pet> pets;
        if(StringUtils.isNotBlank(petBreed)){
            pets = petService.list(Integer.parseInt(petBreed));
        }else{
            pets = petService.list(null);
        }
        HashMap<String,Object> retMap = new HashMap<>();
        //把宠物列表放到map中
        retMap.put("pets",pets);
        //查询所有品种
        PetBreedEnum[] petBreeds = PetBreedEnum.values();
        List<HashMap<String,Object>> breedList = new ArrayList<>();
        for (PetBreedEnum breed : petBreeds) {
            HashMap<String,Object> breedMap = new HashMap<>();
            breedMap.put("value",breed.getValue());
            breedMap.put("name",breed.name());
            breedList.add(breedMap);
        }
        //把所有品种放到map中
        retMap.put("breedList",breedList);
        resp.setCharacterEncoding("UTF-8");
        PrintWriter pw = resp.getWriter();
        pw.write(JSON.toJSONString(AjaxResult.success(retMap)));
        pw.flush();
        pw.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
